package service;

import dao.ComputerDao;
import model.Computer;
import java.util.List;
import java.util.Scanner;

public class ComputerService {
    private ComputerDao computerDao;
    private Scanner scanner;

    public ComputerService() {
        this.computerDao = new ComputerDao();
        this.scanner = new Scanner(System.in);
    }

    public void addComputer() {
        System.out.println("\n=== 添加电脑 ===");
        System.out.print("请输入电脑ID: ");
        String id = scanner.nextLine();

        if (computerDao.findComputerById(id) != null) {
            System.out.println("电脑ID已存在！");
            return;
        }

        System.out.print("请输入品牌: ");
        String brand = scanner.nextLine();
        System.out.print("请输入型号: ");
        String model = scanner.nextLine();
        System.out.print("请输入配置: ");
        String configuration = scanner.nextLine();
        System.out.print("请输入价格: ");
        double price = scanner.nextDouble();
        System.out.print("请输入库存数量: ");
        int stock = scanner.nextInt();
        scanner.nextLine();

        Computer computer = new Computer(id, brand, model, configuration, price, stock);
        computerDao.addComputer(computer);
        System.out.println("电脑添加成功！");
    }

    public void viewAllComputers() {
        System.out.println("\n=== 所有电脑信息 ===");
        List<Computer> computers = computerDao.getAllComputers();

        if (computers.isEmpty()) {
            System.out.println("暂无电脑信息！");
            return;
        }

        System.out.println("ID\t品牌\t型号\t配置\t\t价格\t\t库存");
        System.out.println("------------------------------------------------------------------------");
        for (Computer computer : computers) {
            System.out.printf("%s\t%s\t%s\t%s\t¥%.2f\t%d\n",
                    computer.getId(), computer.getBrand(), computer.getModel(),
                    computer.getConfiguration(), computer.getPrice(), computer.getStock());
        }
    }

    public void updateComputerStock() {
        System.out.println("\n=== 更新电脑库存 ===");
        System.out.print("请输入电脑ID: ");
        String id = scanner.nextLine();

        Computer computer = computerDao.findComputerById(id);
        if (computer == null) {
            System.out.println("电脑不存在！");
            return;
        }

        System.out.print("请输入新的库存数量: ");
        int newStock = scanner.nextInt();
        scanner.nextLine();

        computer.setStock(newStock);
        computerDao.updateComputer(computer);
        System.out.println("库存更新成功！");
    }

    public Computer findComputerById(String id) {
        return computerDao.findComputerById(id);
    }

    public void updateComputer(Computer computer) {
        computerDao.updateComputer(computer);
    }
}